import { createRouter, createWebHistory } from 'vue-router'
// 导入布局组件
import AdminLayout from '@/layouts/AdminLayout.vue'
// 导入页面组件
import LoginView from '@/views/Login/index.vue'
import HomeView from '@/views/Home/index.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginView,
    meta: { 
      requiresLogin: false,
      title: '登录',
      hidden: true
    }
  },
  {
    path: '/',
    component: AdminLayout,
    redirect: '/home',
    meta: {
      title: '首页'
    },
    children: [
      {
        path: 'home',
        name: 'Home',
        component: HomeView,
        meta: { 
          requiresLogin: true,
          title: '首页',
          icon: 'House'
        }
      },
      {
        path: 'user',
        name: 'User',
        meta: { 
          requiresLogin: true,
          title: '用户管理',
          icon: 'User'
        },
        children: [
          {
            path: 'profile',
            name: 'Profile',
            component: () => import('@/views/Profile/index.vue'),
            meta: {
              requiresLogin: true,
              title: '个人中心',
              icon: 'User'
            }
          },
          {
            path: 'userList',
            name: 'UserList',
            component: () => import('@/views/User/index.vue'),
            meta: { 
              requiresLogin: true,
              title: '用户列表',
              icon: 'Document'
            }
          },
          {
            path: 'adminList',
            name: 'AdminList',
            component: () => import('@/views/Admin/index.vue'),
            meta: { 
              requiresLogin: true,
              title: '管理员列表',
              icon: 'Document'
            }
          }
        ]
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫：拦截需要登录的页面
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.meta.requiresLogin && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router